import React, { useEffect, useState } from "react";

interface Message {
  // 根据你的实际消息结构定义类型
  text?: string;
  [key: string]: any;
}

function EventSourceComponent() {
  const [messages, setMessages] = useState<Message[]>([]);

  useEffect(() => {
    async function startStream() {
      try {
        const resp = await fetch(
          "http://localhost:8001/api/v1/chat_vllm/stream/",
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              model: "vllm",
              messages: [{ role: "user", content: "请写一首诗" }],
            }),
          }
        );

        if (!resp.ok || !resp.body) throw new Error(resp.statusText);

        const reader = resp.body.getReader();
        const decoder = new TextDecoder("utf-8");

        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          const chunk = decoder.decode(value, { stream: true });
          const lines = chunk
            .split("\n")
            .filter((line) => line.startsWith("data: "));

          lines.forEach((line) => {
            try {
              console.log(line);
              // 后端数据使用json包裹能解决部分"\n"处理的问题
              // 然后模型生成的大段可能包含"\n"的数据在后端就拆成一行一行发送。貌似这种写法就不用发送DONE这样的结束消息了
              const message = JSON.parse(line.replace("data: ", ""));
              console.log(message);
              setMessages((prevMessages) => [...prevMessages, message]);
            } catch (error) {
              console.error("Failed to parse event data:", error);
            }
          });
        }
      } catch (error) {
        console.error("Error fetching event source:", error);
      }
    }

    startStream();

    return () => {
      // Cleanup code here if necessary
    };
  }, []);

  return (
    <div>
      {messages.map((msg, index) => (
        <p key={index}>{JSON.stringify(msg)}</p>
      ))}
    </div>
  );
}

export default EventSourceComponent;
